<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Model\Bill;
use App\Model\Device;

use App\Model\Distributors;
use App\Model\Order;
use App\Model\Station;
use App\Model\User;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Redis\Redis;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use App\Controller\AbstractController;

class StaticsController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Device $device;

    #[inject]
    protected Distributors $distributors;


    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**获取后台背景图
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getBackImage():ResponseInterface
    {
        $data['url'] = $this->redis->get('back_admin_img');
        return $this->success($data);
    }

    /**卡片统计
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function scrollNum(RequestInterface $request):ResponseInterface{
        $info = $this->distributors->getInfo($request);
        $distributor = $request->input('distributor_id');
        $stations = $request->input('station_id');
        if($stations && !is_array($stations)){
            $stations = json_decode($stations);
        }
// 基础查询（不包含 inline 条件）
        $baseQuery = Device::query();
// 根据用户等级动态添加分销商条件
        if ($info['level'] == 1) {
            $baseQuery->where('distributor_id', $info['id']);
            if (!empty($distributor)) {
                $baseQuery->where('child_distributor_id', $distributor);
            }
        } else {
            $baseQuery->where('child_distributor_id', $info['id']);
        }
        if($stations){
            $baseQuery->whereIn('station_id',$stations);
        }
// 统计在线设备
        $data['online'] = (clone $baseQuery)->where('inline', 1)->count();
// 统计离线设备
        $data['offline'] = (clone $baseQuery)->where('inline', 0)->count();
        $time = $request->input('time');
        $orderQuery = Order::query()->where('is_draw',0);
//        $billQuery = Bill::query()->where('account_type','App\Model\Distributors');
        if(!$time){
          $time[0] = date('Y-m-d');
          $time[1] = date('Y-m-d');
        }
        $startDate = new \DateTime($time[0]);
        $endDate = new \DateTime($time[1]);
        $interval = $startDate->diff($endDate);
// 计算绝对天数差（无论日期顺序）
        if ($interval->days > 90) {
            return $this->error(1001,'起止日期不可超过3个月');
        }
//        $stationQuery = Station::query();
        if(!empty($distributor)){
            $orderQuery->where('distributor_id',$distributor);
//            $stationQuery->where('distributor_id',$distributor);
//            $billQuery->where('account_id',$distributor);
        }else{
            if($info['level'] == 2){
                $orderQuery->where('distributor_id',$info['id']);
//                $stationQuery->where('distributor_id',$info['id']);
//                $billQuery->where('account_id',$info['id']);
            }else{
                $distributors = $this->distributors
                    ->where('parent_id',$info['id'])
                    ->orWhere('id',$info['id'])
                    ->pluck('id')->toArray();
                if($info['id'] != 135) {
                    $orderQuery->whereIn('distributor_id', $distributors);
                }else{
                    $data['end_order'] = 0;
                    $data['end_time'] = 0;
                    $data['return_fee'] = 0;
                    $data['power_fee'] = 0;
                    $data['use_elec'] = 0;
                    $data['using_order'] = 0;
                    return $this->success($data);
                }
//                $stationQuery->whereIn('distributor_id',$distributors);
//                $billQuery->whereIn('account_id',$distributors);
            }
        }
        if($stations){
            $orderQuery->whereIn('station_id',$stations);
        }
  //      $data['bill_amount'] = (float)$billQuery->whereBetween('created_at',[$time[0].' 00:00:00',$time[1].' 23:59:59'])->sum('fee');
        $data['using_order']=(clone $orderQuery)->where('status',Order::STATUS_USING)
            ->whereBetween('created_at',[$time[0].' 00:00:00',$time[1].' 23:59:59'])->count();
        $result = (clone $orderQuery)
            ->whereIn('status', [Order::STATUS_REFUNDED, Order::STATUS_END])
            ->whereBetween('stop_at', [$time[0].' 00:00:00', $time[1].' 23:59:59'])
            ->selectRaw('
        COUNT(*) as order_count,
        COALESCE(SUM(duration_seconds), 0) as total_duration,
        COALESCE(SUM(return_fee), 0) as total_return_fee,
        COALESCE(SUM(power_fee), 0) as total_power_fee
    ')->first();
        $data['end_order'] = $result->order_count;
        $data['end_time'] = $result->total_duration;
        $data['return_fee'] = $result->total_return_fee;
        $data['power_fee'] = $result->total_power_fee;
        if($data['end_time']>0){
            $data['end_time'] = round($data['end_time']/3600,2);
        }
        $data['use_elec'] = (clone $orderQuery)->whereIn('status',[Order::STATUS_REFUNDED,Order::STATUS_END])
            ->whereBetween('created_at',[$time[0].' 00:00:00',$time[1].' 23:59:59'])
            ->where('is_fail',1)->sum('surplus_electricity');
        if($data['use_elec'] >0){
            $data['use_elec'] = round($data['use_elec']/100,2);
        }
  //      $data['stations'] = $stationQuery->count();
        return $this->success($data);
    }




    /**获取lineChart
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getMonth(RequestInterface $request):ResponseInterface{


        $info = $this->distributors->getInfo($request);
        $distributor = $request->input('distributor_id');
        $time = $request->input('time');
        // 定义起始日期和结束日期
        $startDate = new \DateTime($time[0]);
        $endDate = new \DateTime($time[1]);
        $interval = $startDate->diff($endDate);

// 计算绝对天数差（无论日期顺序）
        if ($interval->days > 31) {
            return $this->error(1001,'因数据量较大，大范围搜索较为占用资源，统计表格数据时起止日期不可超过1个月');
        }
// 初始化存储日期的数组
        $data['line'] = [];
        $data['data'] =[];
        $data['elec'] = [];
        if(empty($distributor)){
            if($info['level'] == 1){
                $distributors = $this->distributors
                    ->where('parent_id',$info['id'])
                    ->orWhere('id',$info['id'])
                    ->pluck('id')->toArray();
             }
            if($info['id'] == 135){
                return $this->success($data);
            }
        }
        $stations = $request->input('station_id');
        if($stations && !is_array($stations)){
            $stations = json_decode($stations);
        }
// 循环生成每一天
        while ($startDate <= $endDate) {
            $data['line'][] = $tempDate = $startDate->format('Y-m-d'); // 格式化为字符串
            $startDate->modify('+1 day'); // 增加一天
            $orderQuery = Order::query()->where('is_draw',0);
            if(!empty($distributor)){
                $orderQuery->where('distributor_id',$distributor);
            }else{
                if($info['level'] == 2){
                    $orderQuery->where('distributor_id',$info['id']);
                }else{
                    $orderQuery->whereIn('distributor_id',$distributors);
                }
            }
            if($stations){
                $orderQuery->whereIn('station_id',$stations);
            }
            $result = (clone $orderQuery)
                ->whereIn('status', [Order::STATUS_REFUNDED, Order::STATUS_END])
                ->whereBetween('stop_at', [$tempDate.' 00:00:00', $tempDate.' 23:59:59'])
                ->selectRaw('
        COUNT(*) as order_count,
        COALESCE(SUM(duration_seconds), 0) as total_duration,
        COALESCE(SUM(return_fee), 0) as total_return_fee,
        COALESCE(SUM(power_fee), 0) as total_power_fee
    ')->first();
            $data['data'][] = $result->order_count;
            $data['end_time'][] = round($result->total_duration?$result->total_duration/3600:0,2);
            $data['return_fee'][] = $result->total_return_fee;
            $data['power_fee'][] = $result->total_power_fee;
            $tempElec = (clone $orderQuery)->whereIn('status',[Order::STATUS_REFUNDED,Order::STATUS_END])
                ->whereBetween('stop_at',[$tempDate.' 00:00:00',$tempDate.' 23:59:59'])
                ->where('is_fail',1)->sum('surplus_electricity');
            if($tempElec >0){
                $data['elec'][] = round($tempElec/100,2);
            }else{
                $data['elec'][] = 0;
            }
        }

         return $this->success($data);
    }
}
